<template>
  <div class="checkup-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>体检管理</h2>
      <p>管理体检流程，包括体检项目执行、结果录入和报告生成</p>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="患者姓名">
          <el-input
            v-model="searchForm.patientName"
            placeholder="请输入患者姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="体检状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待体检" value="pending" />
            <el-option label="体检中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="体检日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item label="负责医生">
          <el-select
            v-model="searchForm.doctor"
            placeholder="请选择医生"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="doctor in doctors"
              :key="doctor.id"
              :label="doctor.name"
              :value="doctor.name"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作栏 -->
    <el-card class="action-card">
      <div class="action-bar">
        <div class="action-left">
          <el-button type="success" @click="handleBatchStart" :disabled="selectedRecords.length === 0">
            <el-icon><VideoPlay /></el-icon>
            批量开始
          </el-button>
          <el-button type="primary" @click="handleBatchComplete" :disabled="selectedRecords.length === 0">
            <el-icon><Check /></el-icon>
            批量完成
          </el-button>
          <el-button type="warning" @click="handleBatchAssign" :disabled="selectedRecords.length === 0">
            <el-icon><User /></el-icon>
            分配医生
          </el-button>
        </div>
        
        <div class="action-right">
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.pending }}</div>
                <div class="stat-label">待体检</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon progress">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.inProgress }}</div>
                <div class="stat-label">体检中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon completed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon today">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.today }}</div>
                <div class="stat-label">今日体检</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 体检记录列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="checkupRecords"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="体检ID" width="120" sortable="custom" />
        
        <el-table-column prop="patientName" label="患者信息" width="150">
          <template #default="{ row }">
            <div class="patient-info">
              <el-avatar :size="32" :src="row.patientAvatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="patient-details">
                <div class="patient-name">{{ row.patientName }}</div>
                <div class="patient-phone">{{ row.patientPhone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="packageName" label="体检套餐" width="150" show-overflow-tooltip />
        
        <el-table-column prop="checkupDate" label="体检日期" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatDate(row.checkupDate) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="{ row }">
            <div class="progress-cell">
              <el-progress
                :percentage="row.progress"
                :stroke-width="6"
                :show-text="false"
              />
              <span class="progress-text">{{ row.progress }}%</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="doctor" label="负责医生" width="100" show-overflow-tooltip />
        
        <el-table-column prop="startTime" label="开始时间" width="150">
          <template #default="{ row }">
            {{ row.startTime ? formatDateTime(row.startTime) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="endTime" label="完成时间" width="150">
          <template #default="{ row }">
            {{ row.endTime ? formatDateTime(row.endTime) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" text @click="handleView(row)">
                查看
              </el-button>
              
              <el-button
                v-if="row.status === 'pending'"
                type="success"
                size="small"
                text
                @click="handleStart(row)"
              >
                开始
              </el-button>
              
              <el-button
                v-if="row.status === 'in_progress'"
                type="warning"
                size="small"
                text
                @click="handleRecord(row)"
              >
                录入
              </el-button>
              
              <el-button
                v-if="row.status === 'in_progress' && row.progress === 100"
                type="primary"
                size="small"
                text
                @click="handleComplete(row)"
              >
                完成
              </el-button>
              
              <el-dropdown trigger="click">
                <el-button type="info" size="small" text>
                  更多<el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleAssignDoctor(row)">
                      <el-icon><User /></el-icon>
                      分配医生
                    </el-dropdown-item>
                    <el-dropdown-item @click="handleViewItems(row)">
                      <el-icon><List /></el-icon>
                      查看项目
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="row.status === 'completed'"
                      @click="handleGenerateReport(row)"
                    >
                      <el-icon><Document /></el-icon>
                      生成报告
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="row.status === 'pending'"
                      divided
                      @click="handleCancel(row)"
                    >
                      <el-icon><Close /></el-icon>
                      取消
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 体检详情对话框 -->
    <CheckupDetail
      v-model:visible="detailVisible"
      :record="currentRecord"
      @start="handleStart"
      @complete="handleComplete"
      @record="handleRecord"
    />
    
    <!-- 结果录入对话框 -->
    <ResultRecord
      v-model:visible="recordVisible"
      :record="currentRecord"
      @success="handleRecordSuccess"
    />
    
    <!-- 分配医生对话框 -->
    <AssignDoctor
      v-model:visible="assignVisible"
      :records="selectedRecords"
      :doctors="doctors"
      @success="handleAssignSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CheckupDetail from '@/components/CheckupDetail.vue'
import ResultRecord from '@/components/ResultRecord.vue'
import AssignDoctor from '@/components/AssignDoctor.vue'

// 响应式数据
const loading = ref(false)
const detailVisible = ref(false)
const recordVisible = ref(false)
const assignVisible = ref(false)
const currentRecord = ref(null)
const selectedRecords = ref([])

// 搜索表单
const searchForm = reactive({
  patientName: '',
  status: '',
  dateRange: [],
  doctor: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 排序
const sortConfig = reactive({
  prop: 'checkupDate',
  order: 'descending'
})

// 模拟数据
const checkupRecords = ref([
  {
    id: 'C001',
    patientId: 1,
    patientName: '张三',
    patientPhone: '13800138001',
    patientAvatar: '',
    packageId: 1,
    packageName: '基础体检套餐',
    checkupDate: '2024-01-20',
    status: 'pending',
    progress: 0,
    doctor: '李医生',
    startTime: '',
    endTime: '',
    createdAt: '2024-01-15 10:30:00'
  },
  {
    id: 'C002',
    patientId: 2,
    patientName: '李四',
    patientPhone: '13800138002',
    patientAvatar: '',
    packageId: 2,
    packageName: '全面体检套餐',
    checkupDate: '2024-01-21',
    status: 'in_progress',
    progress: 60,
    doctor: '王医生',
    startTime: '2024-01-21 08:30:00',
    endTime: '',
    createdAt: '2024-01-14 15:20:00'
  },
  {
    id: 'C003',
    patientId: 3,
    patientName: '王五',
    patientPhone: '13800138003',
    patientAvatar: '',
    packageId: 1,
    packageName: '基础体检套餐',
    checkupDate: '2024-01-19',
    status: 'completed',
    progress: 100,
    doctor: '张医生',
    startTime: '2024-01-19 09:00:00',
    endTime: '2024-01-19 11:30:00',
    createdAt: '2024-01-12 11:45:00'
  },
  {
    id: 'C004',
    patientId: 4,
    patientName: '赵六',
    patientPhone: '13800138004',
    patientAvatar: '',
    packageId: 3,
    packageName: '高端体检套餐',
    checkupDate: '2024-01-18',
    status: 'completed',
    progress: 100,
    doctor: '陈医生',
    startTime: '2024-01-18 08:00:00',
    endTime: '2024-01-18 12:00:00',
    createdAt: '2024-01-10 16:20:00'
  },
  {
    id: 'C005',
    patientId: 5,
    patientName: '孙七',
    patientPhone: '13800138005',
    patientAvatar: '',
    packageId: 2,
    packageName: '全面体检套餐',
    checkupDate: '2024-01-22',
    status: 'in_progress',
    progress: 30,
    doctor: '刘医生',
    startTime: '2024-01-22 09:30:00',
    endTime: '',
    createdAt: '2024-01-08 14:10:00'
  }
])

const doctors = ref([
  { id: 1, name: '张医生', title: '主任医师' },
  { id: 2, name: '李医生', title: '副主任医师' },
  { id: 3, name: '王医生', title: '主治医师' },
  { id: 4, name: '陈医生', title: '住院医师' },
  { id: 5, name: '刘医生', title: '主治医师' }
])

// 统计数据
const stats = computed(() => {
  const pending = checkupRecords.value.filter(item => item.status === 'pending').length
  const inProgress = checkupRecords.value.filter(item => item.status === 'in_progress').length
  const completed = checkupRecords.value.filter(item => item.status === 'completed').length
  const today = checkupRecords.value.filter(item => {
    const today = new Date().toISOString().split('T')[0]
    return item.checkupDate === today
  }).length
  
  return {
    pending,
    inProgress,
    completed,
    today
  }
})

// 生命周期
onMounted(() => {
  loadCheckupRecords()
})

// 方法
const loadCheckupRecords = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    pagination.total = checkupRecords.value.length
  } catch (error) {
    ElMessage.error('加载体检记录失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadCheckupRecords()
}

const handleReset = () => {
  Object.assign(searchForm, {
    patientName: '',
    status: '',
    dateRange: [],
    doctor: ''
  })
  handleSearch()
}

const handleRefresh = () => {
  loadCheckupRecords()
}

const handleView = (record) => {
  currentRecord.value = record
  detailVisible.value = true
}

const handleStart = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要开始体检 ${record.id} 吗？`,
      '开始体检',
      {
        confirmButtonText: '开始',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 模拟API调用
    record.status = 'in_progress'
    record.startTime = new Date().toLocaleString('zh-CN')
    
    ElMessage.success('体检已开始')
  } catch {
    // 用户取消
  }
}

const handleRecord = (record) => {
  currentRecord.value = record
  recordVisible.value = true
}

const handleComplete = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要完成体检 ${record.id} 吗？`,
      '完成体检',
      {
        confirmButtonText: '完成',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    // 模拟API调用
    record.status = 'completed'
    record.progress = 100
    record.endTime = new Date().toLocaleString('zh-CN')
    
    ElMessage.success('体检已完成')
  } catch {
    // 用户取消
  }
}

const handleCancel = async (record) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入取消原因',
      '取消体检',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入取消原因',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '请输入取消原因'
          }
          return true
        }
      }
    )
    
    // 模拟API调用
    record.status = 'cancelled'
    
    ElMessage.success('体检已取消')
  } catch {
    // 用户取消
  }
}

const handleAssignDoctor = (record) => {
  selectedRecords.value = [record]
  assignVisible.value = true
}

const handleViewItems = (record) => {
  ElMessage.info(`查看体检项目功能待实现 - 体检ID: ${record.id}`)
}

const handleGenerateReport = (record) => {
  ElMessage.info(`生成报告功能待实现 - 体检ID: ${record.id}`)
}

const handleBatchStart = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量开始选中的 ${selectedRecords.value.length} 个体检吗？`,
      '批量开始',
      {
        confirmButtonText: '开始',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 模拟API调用
    selectedRecords.value.forEach(record => {
      if (record.status === 'pending') {
        record.status = 'in_progress'
        record.startTime = new Date().toLocaleString('zh-CN')
      }
    })
    
    ElMessage.success('批量开始成功')
    selectedRecords.value = []
  } catch {
    // 用户取消
  }
}

const handleBatchComplete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量完成选中的 ${selectedRecords.value.length} 个体检吗？`,
      '批量完成',
      {
        confirmButtonText: '完成',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    // 模拟API调用
    selectedRecords.value.forEach(record => {
      if (record.status === 'in_progress') {
        record.status = 'completed'
        record.progress = 100
        record.endTime = new Date().toLocaleString('zh-CN')
      }
    })
    
    ElMessage.success('批量完成成功')
    selectedRecords.value = []
  } catch {
    // 用户取消
  }
}

const handleBatchAssign = () => {
  assignVisible.value = true
}

const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

const handleSelectionChange = (selection) => {
  selectedRecords.value = selection
}

const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop
  sortConfig.order = order
  loadCheckupRecords()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadCheckupRecords()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadCheckupRecords()
}

const handleRecordSuccess = () => {
  recordVisible.value = false
  loadCheckupRecords()
}

const handleAssignSuccess = () => {
  assignVisible.value = false
  selectedRecords.value = []
  loadCheckupRecords()
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待体检',
    in_progress: '体检中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.checkup-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left,
.action-right {
  display: flex;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}

.stat-icon.progress {
  background: linear-gradient(135deg, #3498db, #2980b9);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #27ae60, #229954);
}

.stat-icon.today {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.patient-details {
  flex: 1;
  min-width: 0;
}

.patient-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
  line-height: 1.2;
}

.patient-phone {
  color: #909399;
  font-size: 12px;
  line-height: 1.2;
}

.progress-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-text {
  font-size: 12px;
  color: #606266;
  min-width: 35px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .action-left,
  .action-right {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .checkup-management {
    padding: 10px;
  }
  
  .stats-cards .el-col {
    margin-bottom: 12px;
  }
  
  .stat-content {
    gap: 12px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .patient-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .progress-cell {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table .cell) {
    padding: 8px 4px;
  }
}

@media (max-width: 480px) {
  .page-header h2 {
    font-size: 20px;
  }
  
  .action-left,
  .action-right {
    flex-direction: column;
  }
  
  .action-left .el-button,
  .action-right .el-button {
    width: 100%;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .pagination-wrapper {
    overflow-x: auto;
  }
  
  :deep(.el-pagination) {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>